const { parse } = require('node-xlsx');
const fs = require("fs");
const { resolve } = require('path');
let originData = require('../asset/i18n/329');
const { validateTrans } = require('../common');
/**
 *  * 将翻译文件中符合规则的翻译内容写入英文文件
 *  * 可能会出现中文有的key在英文中找不到
 * @param {object} opts 
 * @param {string} [opts.fromFileName] 翻译来源path
 * @param {string} [opts.toFileName] 结果储存
 * @param {string} [opts.keyIndex] 要替换的内容对应key所在xls column
 * @param {string} [opts.transOutIndex] 要替换的内容所在xls column
 * @param {string} [opts.replaceOriginData] 要替换的数据
 */
function writeXls2Js(opts) {

    let {
        fromFileName = 'i18n',
        toFileName = 'i18n',
        keyIndex = 0,
        transOutIndex = 1,
        replaceOriginData
    } = opts;

    // 文件加后缀
    if (!fromFileName.endsWith(".xls")) {
        fromFileName = `${fromFileName}.xls`
    }
    if (!toFileName.endsWith(".js")) {
        toFileName = `${toFileName}.js`
    }

    // 读取xls文件
    let writePath = resolve(__dirname, '../asset/xls', fromFileName)
    let [{ data }] = parse(writePath);

    // 获取到翻译后的数据
    let translatedData = data.splice(2); // 移除标题栏

    // let outData = JSON.parse(JSON.stringify(replaceOriginData))

    // return console.log(translatedData[0])
    // 遍历xls数据
    translatedData.forEach(value => {
        const zh = value[0];
        // const en = value[5];
        const fr = value[1];
        findAndReplaceValue(zh, replaceOriginData, fr)
        // findAndReplaceValue(zh, replaceOriginData, transOutIndex == 5 ? en : fr)

    })
    let outPath = resolve(__dirname, '../asset/i18n', toFileName)
    fs.writeFileSync(outPath, `export default  ${JSON.stringify(replaceOriginData)}`) // 写国际化文件
}

function findAndReplaceValue(rule, originData, replaceData) {
    try {
        if (!!!rule) return;

        for (let key in originData) {

            if (typeof originData[key] === 'string') {
                if (originData[key] === rule) {
                    console.log(replaceData);
                    return originData[key] = replaceData
                }
            } else {
                findAndReplaceValue(rule, originData[key], replaceData)
            }
        }
    } catch (error) { }
}


writeXls2Js({
    fromFileName: '329',
    toFileName: 'fr',
    transOutIndex: 5,
    replaceOriginData: originData
})
// writeXls2Js({
//     fromFileName: '328',
//     toFileName: 'fr',
//     transOutIndex: 6,
//     replaceOriginData: originData
// })
